//应用的APPID
var _appID = "101280866";
//登录授权后的回调地址，设置为当前url
var _redirectURI = "http://wap.soolife.cn/view/account/login_qq.html";
//跳转服务端登录url
var _getUserInfoURI = "http://wap.soolife.cn/server/qqlogin.php";

var _accessToken;
//初始构造请求
if (window.location.hash.length == 0) {
    var path = 'https://graph.qq.com/oauth2.0/authorize?';
    var queryParams = ['client_id=' + _appID,
        'redirect_uri=' + _redirectURI,
        'scope=get_user_info,list_album,upload_pic,add_feeds,do_like', 'response_type=token'];

    var query = queryParams.join('&');
    var url = path + query;
    window.location.href = url;
}
//在成功授权后回调时location.hash将带有access_token信息，开始获取openid
else {
    //获取access token
    var accessToken = window.location.hash.substring(1);
    var map = toParamMap(accessToken);

    //记录accessToken
    _accessToken = map.access_token;

    //使用Access Token来获取用户的OpenID
    var path = "https://graph.qq.com/oauth2.0/me?";
    var queryParams = ['access_token=' + map.access_token, 'callback=callback'];
    var query = queryParams.join('&');
    var url = path + query;
    openImplict(url);
}


//切割字符串转换参数表
function toParamMap(str) {
    var map = {};
    var segs = str.split("&");
    for (var i in segs) {
        var seg = segs[i];
        var idx = seg.indexOf('=');
        if (idx < 0) {
            continue;
        }
        var name = seg.substring(0, idx);
        var value = seg.substring(idx + 1);
        map[name] = value;
    }
    return map;
}

//隐式获取url响应内容(JSONP)
function openImplict(url) {
    var script = document.createElement('script');
    script.src = url;
    document.body.appendChild(script);
}

//获得openid的回调
function callback(obj) {
    //向服务端传输access_token及openid参数
    var getuserinfoUrl = _getUserInfoURI + "?access_token=" + _accessToken + "&open_id=" + obj.openid;
    $.ajax({
        type: "GET", url: getuserinfoUrl
    }).done(function (res) {
        var response = JSON.parse(res);
        var userinfo = {typeid: 2, openid: obj.openid, name: response.nickname};
        // 验证用户信息
        var _verfiyAccountModel = new verfiyAccountModel();
        _verfiyAccountModel.verifyAccount(userinfo);
    });
}